package com.andnnl.pool.user;

import com.andnnl.pool.Msg;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 顺序处理消息
 * Created by chenss on 2021/6/23.
 */
public class OneUser<T> extends AbsUser<T> {
    private final ConcurrentLinkedQueue<Msg<T>> queue = new ConcurrentLinkedQueue<>();//用户多的情况下，用Linked，省内存

    public OneUser(String name) {
        this.name = name;
    }

    public OneUser(String name,int batchSize) {
        this.name = name;
        this.batchSize = batchSize;
    }

    @Override
    public List<Msg<T>> takeMsg() {
        List<Msg<T>> list = new ArrayList<>();
        //忽略处理时，返回空
        if (isPause()) {
            return list;
        }
        int i = 0;
        while (i++ < batchSize) {
            Msg<T> m = queue.poll();//先从优先队列取
            if (m == null) {
                break;
            }
            dataSize.addAndGet(-m.getDataSize());//取出的时候，减掉
            list.add(m);
        }
        return list;
    }

    @Override
    public boolean isAllEmpty() {
        return queue.isEmpty();
    }

    @Override
    public void addMsg(Msg<T> msg) {
        msg.setUser(this);
        dataSize.addAndGet(msg.getDataSize());//累计总的dataSize
        queue.add(msg);
    }


    public ConcurrentLinkedQueue<Msg<T>> getQueue() {
        return queue;
    }


    @Override
    public int getTotalSize() {
        return queue.size();
    }


}
